<template>
	<view class="uni-column m-t-2">
		<page-head :headTitle=chatData.to_name :returnButton="true" @clickLeftReturn="clickLeftReturn"></page-head>
		<view class="content" id="content" :style="{height:style.contentViewHeight+'px'}">
			<scroll-view id="scrollview"   scroll-y="true" :style="{height:style.contentViewHeight+'px'}" :scroll-with-animation="true"
			    :scroll-top="scrollTop">
				<message-show v-for="(message,index) in messages" :key="index" v-bind:message="message" :id="index"></message-show>
				<view id="bottom"></view>
			</scroll-view>
		</view>
		<view class="foot">
			<chat-input @send-message="getInputMessage" ></chat-input>
		</view>
	</view>
</template>

<script>
	import chatInput from '@/components/common/chatinput.vue'
	import messageShow from '@/components/common/messageshow.vue'
	import pageHead from '@/components/common/page-head.vue'
	export default {
		data() {
			return {
				style: {
					pageHeight: 0,
					contentViewHeight: 0,
					footViewHeight: 90,
					mitemHeight: 0,
				},
				scrollTop: 0,
				messages: [],
				chatData: {}
			}
		},
		onLoad(e) {
			uni.closeSocket();
			this.ssid = e.ssid;
			this.getChatData();
		},
		components: {
			chatInput,
			messageShow,
			pageHead
		},
		created: function () { 
			const res = uni.getSystemInfoSync();
			this.style.pageHeight = res.windowHeight;
			this.style.contentViewHeight = res.windowHeight - 35 - uni.getSystemInfoSync().screenWidth / 750 * (100); //像素
		},
		methods: {
			clickLeftReturn(){
				uni.closeSocket();
				const pages = getCurrentPages() ;
				if(pages.length >1) {
					uni.navigateBack({
						delta: 1
					});
				}else{
					//返回上一页失败后强制回到首页
					uni.redirectTo({
						url: '../user/index/index'
					})
				}
			},
			//获取聊天信息
			getChatData: function() {
				var _this = this;
				this.$myRequest({
					method:'POST',
					url:'/api/chat/info',
					data:{
						ssid: this.ssid
					}
				}).then(res=>{
					console.log(res);
					if(res.data.code == 1){
						this.chatData = res.data.data;
						uni.connectSocket({
							url: this.chatData.ws_link
						});
						uni.onSocketOpen(function(res){_this.wsLogin(res)});
						uni.onSocketMessage(function(res){_this.wsOnMessage(res)});
						uni.onSocketClose(function (res) {
						  console.log('WebSocket 已关闭！');
						});
					}
				})
			},
			wsLogin: function(res) {
				var loginData = '{"type":"login","ssid":"'+this.chatData.ssid+'","my_id":"'+this.chatData.my_id+'","to_id":"'+this.chatData.to_id+'"}';
				//console.log("websocket握手成功，发送登录数据:"+loginData);
				uni.sendSocketMessage({
					data: loginData
				});
			},
			wsOnMessage: function(res) {
				//console.log('收到服务器内容：' + res.data);
				var data = JSON.parse(res.data);
				switch(data.type){
					// 服务端ping客户端
					case 'ping':
						uni.sendSocketMessage({
							data: '{"type":"pong"}'
						});
						break;
					// 登录成功
					case 'login':
						var chatList = data.chat_list;
						var vuser, vavatar;
						chatList.forEach(item=>{
							if (item.user_id == this.chatData.my_id) {
								vuser = 'customer';
								vavatar = this.chatData.my_avatar;
							} else {
								vuser = 'home';
								vavatar = this.chatData.to_avatar;
							}
							this.messages.push({
								user: vuser,
								avatar: vavatar,
								type: 'head', //input,content 
								content: item.content,
								time: item.sent_at
							});
						});
						break;
					// 发言
					case 'say':
						if (data.user_id == this.chatData.my_id) {
							vuser = 'customer';
							vavatar = this.chatData.my_avatar;
						} else {
							vuser = 'home';
							vavatar = this.chatData.to_avatar;
						}
						this.messages.push({
							user: vuser,
							avatar: vavatar,
							type: 'head', //input,content 
							content: data.content,
							time: data.sent_at
						});
						break;
				}
				setTimeout(() => {
					this.scrollToBottom();
				},1)
			},
			getInputMessage: function (message) { //获取子组件的输入数据
				// console.log(message);
				this.addMessage('customer', message.content, false);
				// this.toRobot(message.content);
			},
			addMessage: function (user, content, hasSub) {
				if (!content) {
					return;
				}
				var msgBody = '{"type":"say","content":"'+content.replace(/"/g, '\\"').replace(/\n/g,'\\n').replace(/\r/g, '\\r')+'"}';
				uni.sendSocketMessage({
					data: msgBody
				});
			},
			scrollToBottom: function () {
				var that = this;
				var query = uni.createSelectorQuery();
				query.selectAll('.m-item').boundingClientRect();
				query.select('#scrollview').boundingClientRect();

				query.exec(function (res) {
					that.style.mitemHeight = 0;
					res[0].forEach(function (rect) {
						// console.info(rect.height);
						that.style.mitemHeight = that.style.mitemHeight + rect.height + 100;
					});
					setTimeout(() => {
						if (that.style.mitemHeight > that.style.contentViewHeight) {
						that.scrollTop = that.style.mitemHeight+130;
						//console.log(that.scrollTop);
					}},1)
				});
			},
			toRobot: function (info) {

				// this.addMessage('home', info, false);
				var apiUrl = 'http://www.tuling123.com/openapi/api';
				uni.request({
					url: apiUrl,
					data: {
						"key": 'acfbca724ea1b5db96d2eef88ce677dc',
						"info": info,
						"userid": 'uni-test'
					},
					success: (res) => {
						this.addMessage('home', res.data.text, false);
						this.scrollToBottom();
						console.log('request success:' + res.data.text);
					},
					fail: (err) => {
						console.log('request fail', err);
						uni.showModal({
							content: err.errMsg,
							showCancel: false
						})
					}
				});
			}
		}
	}
</script>

<style>
	.uni-column {
		display: flex;
		flex-direction: column;
	}
	.content {

		display: flex;
		flex: 1;
		margin-bottom: 100px;
		 
	}
	.foot {
		position: fixed;
		width: 100%;
		height: 100rpx;
		min-height: 90rpx;
		left: 0px;
		bottom: 0px;
		overflow: hidden;
	}
</style>
